from rest_framework.response import Response
from rest_framework import status
from typing import Any, Optional, Dict
import logging

logger = logging.getLogger(__name__)

class ApiResponse:
    """统一API响应格式"""
    
    @staticmethod
    def success(data: Any = None, message: str = "操作成功", code: int = 0, http_status: int = status.HTTP_200_OK) -> Response:
        """成功响应"""
        response_data = {
            'success': True,
            'code': code,
            'data': data,
            'message': message
        }
        return Response(response_data, status=http_status)
    
    @staticmethod
    def error(message: str = "操作失败", code: int = -1, data: Any = None, http_status: int = status.HTTP_400_BAD_REQUEST) -> Response:
        """错误响应"""
        response_data = {
            'success': False,
            'code': code,
            'data': data,
            'message': message
        }
        logger.error(f"API Error: {message}, Code: {code}")
        return Response(response_data, status=http_status)
    
    @staticmethod
    def paginated_success(data: Dict, message: str = "获取成功", code: int = 0) -> Response:
        """分页数据成功响应"""
        response_data = {
            'success': True,
            'code': code,
            'data': {
                'results': data.get('results', []),
                'count': data.get('count', 0),
                'next': data.get('next'),
                'previous': data.get('previous')
            },
            'message': message
        }
        return Response(response_data, status=status.HTTP_200_OK)

# 错误码定义
class ErrorCode:
    """统一错误码定义"""
    # 成功
    SUCCESS = 0
    
    # 通用错误 (-1 ~ -99)
    GENERAL_ERROR = -1
    UNKNOWN_ERROR = -2
    
    # 请求相关错误 (1000 ~ 1099)
    VALIDATION_ERROR = 1001
    MISSING_PARAMETER = 1002
    INVALID_PARAMETER = 1003
    
    # 认证授权错误 (1100 ~ 1199)
    AUTHENTICATION_ERROR = 1101
    PERMISSION_ERROR = 1102
    TOKEN_EXPIRED = 1103
    TOKEN_INVALID = 1104
    
    # 资源错误 (1200 ~ 1299)
    NOT_FOUND_ERROR = 1201
    RESOURCE_EXISTS = 1202
    RESOURCE_CONFLICT = 1203
    
    # 数据库错误 (1300 ~ 1399)
    DATABASE_ERROR = 1301
    DATABASE_CONNECTION_ERROR = 1302
    
    # 业务逻辑错误 (2000 ~ 2999)
    PROJECT_NAME_EXISTS = 2001
    PROJECT_LIMIT_EXCEEDED = 2002
    API_KEY_GENERATION_FAILED = 2003